define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            const setupTitleData =  {
                'meet': {'title': 'Basic configuration','value': 'meet'},
                'wxPayment': {'title': 'WeChat payment configuration','value': 'wxPayment'},
                'wxMiniProgram': {'title': 'WeChat applet configuration','value': 'wxMiniProgram'},
                'user': {'title': 'Member configuration','value': 'user'},
                'share': {'title': 'Share configuration','value': 'share'},
                'order': {'title': 'Order configuration','value': 'order'},
                'services': {'title': 'Third-party service configuration','value': 'services'},
                'mall': {'title': 'Mall configuration','value': 'mall'},
                'wechat': {'title': 'WeChat configuration','value':'wechat'}
            };
            $(document).on("click", ".btn-setup", function () {
                let key = $(this).data('key');
                Backend.api.open('meet/config/platform/group/' + setupTitleData[key].value, __(setupTitleData[key].title),{area:['70%','70%']});
            });

            $("form.edit-form").data("validator-options", {
                display: function (elem) {
                    return $(elem).closest('tr').find("td:first").text();
                }
            });
            Form.api.bindevent($("form.edit-form"));

            //不可见的元素不验证
            $("form#add-form").data("validator-options", {
                ignore: ':hidden',
                rules: {
                    content: function () {
                        return ['radio', 'checkbox', 'select', 'selects'].indexOf($("#add-form select[name='row[type]']").val()) > -1;
                    },
                    extend: function () {
                        return $("#add-form select[name='row[type]']").val() == 'custom';
                    }
                }
            });
            Form.api.bindevent($("form#add-form"), function (ret) {
                setTimeout(function () {
                    location.reload();
                }, 1500);
            });

            //渲染关联显示字段和存储字段
            var renderselect = function (id, data, defaultvalue) {
                var html = [];
                for (var i = 0; i < data.length; i++) {
                    html.push("<option value='" + data[i].name + "' " + (defaultvalue == data[i].name ? "selected" : "") + " data-subtext='" + data[i].title + "'>" + data[i].name + "</option>");
                }
                var select = $(id);
                $(select).html(html.join(""));
                select.trigger("change");
                if (select.data("selectpicker")) {
                    select.selectpicker('refresh');
                }
            };
            //关联表切换
            $(document).on('change', "#c-selectpage-table", function (e, first) {
                var that = this;
                Fast.api.ajax({
                    url: "meet/config/get_fields_list",
                    data: {table: $(that).val()},
                }, function (data, ret) {
                    renderselect("#c-selectpage-primarykey", data.fieldList, first ? $("#c-selectpage-primarykey").data("value") : '');
                    renderselect("#c-selectpage-field", data.fieldList, first ? $("#c-selectpage-field").data("value") : '');
                    return false;
                });
                return false;
            });
            //如果编辑模式则渲染已知数据
            if (['selectpage', 'selectpages'].indexOf($("#c-type").val()) > -1) {
                $("#c-selectpage-table").trigger("change", true);
            }

            //切换类型时
            $(document).on("change", "#c-type", function () {
                var value = $(this).val();
                $(".tf").addClass("hidden");
                $(".tf.tf-" + value).removeClass("hidden");
                if (["selectpage", "selectpages"].indexOf(value) > -1 && $("#c-selectpage-table option").length == 1) {
                    //异步加载表列表
                    Fast.api.ajax({
                        url: "meet/config/get_table_list",
                    }, function (data, ret) {
                        renderselect("#c-selectpage-table", data.tableList);
                        return false;
                    });
                }
            });

            //切换显示隐藏变量字典列表
            $(document).on("change", "form#add-form select[name='row[type]']", function (e) {
                $("#add-content-container").toggleClass("hide", ['select', 'selects', 'checkbox', 'radio'].indexOf($(this).val()) > -1 ? false : true);
            });

            //选择规则
            $(document).on("click", ".rulelist > li > a", function () {
                var ruleArr = $("#rule").val() == '' ? [] : $("#rule").val().split(";");
                var rule = $(this).data("value");
                var index = ruleArr.indexOf(rule);
                if (index > -1) {
                    ruleArr.splice(index, 1);
                } else {
                    ruleArr.push(rule);
                }
                $("#rule").val(ruleArr.join(";"));
                $(this).parent().toggleClass("active");
            });

            //添加向发件人发送测试邮件按钮和方法
            $('input[name="row[mail_from]"]').parent().next().append('<a class="btn btn-info testmail">' + __('Send a test message') + '</a>');
            $(document).on("click", ".testmail", function () {
                var that = this;
                Layer.prompt({title: __('Please input your email'), formType: 0}, function (value, index) {
                    Backend.api.ajax({
                        url: "meet/config/emailtest",
                        data: $(that).closest("form").serialize() + "&receiver=" + value
                    });
                });

            });

            //删除配置
            $(document).on("click", ".btn-delcfg", function () {
                var that = this;
                Layer.confirm(__('Are you sure you want to delete this item?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    Backend.api.ajax({
                        url: "meet/config/del",
                        data: {name: $(that).data("name")}
                    }, function () {
                        $(that).closest("tr").remove();
                        Layer.close(index);
                    });
                });

            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        platform: function () {
            if(!registerCoupon){
                registerCoupon = [];
            }

            if(!shareCoupon){
                shareCoupon = [];
            }

            Controller.api.registerCouponTemplate(registerCoupon);

            Controller.api.shareCouponTemplate(shareCoupon);

            $(document).on('click','.btn-register_coupon',function () {
                Fast.api.open('meet/coupon_template/template', __('Choose'), {
                    area: ['80%','80%'],
                    callback: function (data) {
                        // 是否新增
                        let append = false;
                        if("undefined" == typeof registerCoupon || registerCoupon === ''){
                            registerCoupon = [];
                        } else {
                            append = true;
                        }

                        outer:
                            for(let i in data.data){
                                //去掉重复
                                for (let ii in registerCoupon) {
                                    if (registerCoupon[ii].id == data.data[i].id) {
                                        continue outer;
                                    }
                                }

                                //默认数量
                                data.data[i].send_number = 1;
                                if (append) {
                                    // 向表单增加一行
                                    $('#table_register').bootstrapTable('append',data.data[i]);
                                }
                                registerCoupon.push(data.data[i]);
                            }

                        if (append) {
                            return;
                        }

                        Controller.api.registerCouponTemplate(registerCoupon);
                    }
                });
            });

            $(document).on('click','.btn-share_coupon',function () {
                Fast.api.open('meet/coupon_template/template', __('Choose'), {
                    area: ['80%','80%'],
                    callback: function (data) {
                        // 是否新增
                        let append = false;
                        if("undefined" == typeof shareCoupon || shareCoupon === ''){
                            shareCoupon = [];
                        } else {
                            append = true;
                        }

                        outer:
                            for(let i in data.data){
                                //去掉重复
                                for (let ii in shareCoupon) {
                                    if (shareCoupon[ii].id == data.data[i].id) {
                                        continue outer;
                                    }
                                }

                                //默认数量
                                data.data[i].send_number = 1;
                                if (append) {
                                    // 向表单增加一行
                                    $('#table_share').bootstrapTable('append',data.data[i]);
                                }
                                shareCoupon.push(data.data[i]);
                            }

                        if (append) {
                            return;
                        }

                        Controller.api.shareCouponTemplate(shareCoupon);
                    }
                });
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            registerCouponTemplate: function (){
                var table = $('#table_register');
                // 初始化表格
                table.bootstrapTable({
                    data: registerCoupon,
                    pk: 'id',
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    showExport: false, //是否可导出数据
                    columns: [
                        [
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: table,
                                events: Table.api.events.operate,
                                formatter: function (value, row, index) {
                                    var html = '<a href="javascript:$(\'#table_register\').bootstrapTable(\'remove\',{field: \'id\', values: ['+row.id+']});registerCoupon = registerCoupon.filter(function(item){return item.id != '+row.id+';});" class="btn btn-xs btn-danger"  data-original-title="删除"><i class="fa fa-trash">删除</i></a>'
                                    return html;
                                }
                            },
                            {field: 'name', title: __('Coupon_name'), operate: 'LIKE'},
                            {field: 'send_number', title: __('Gift quantity'),formatter: function(value, row, index) {
                                    return '<input name="row[register_send]['+index+'][id]" value="'+row.id+'" type="hidden" />' +
                                        '<input name="row[register_send]['+index+'][id]" value="'+row.id+'" type="hidden" />' +
                                        '<input data-rule="required;integer;range(0~);" name="row[register_send]['+index+'][send_number]" type="number" style="width: 100px" class="form-control" min="1" value="' + value + '" onchange="javascript:registerCoupon['+index+'].send_number = this.value" /> ';
                                }},
                            {field: 'money', title: __('Preferential content'), operate: false, formatter: function (value, row, index) {
                                    return __('%s yuan less than %s yuan',row.limit,row.money);
                                }},
                            {field: 'validity', title: __('Validity'), operate:false,formatter: function (value, row, index) {
                                    if(parseInt(row.validity_type) === 1){
                                        if(row.validity_days > 0){
                                            return __('Valid for %s days after receiving',row.validity_days);
                                        }else{
                                            return __('Permanently valid');
                                        }
                                    }else{
                                        return row.start_time_text + ' - ' + row.end_time_text;
                                    }
                                }},
                        ]
                    ],

                });
            },
            shareCouponTemplate: function (){
                var table = $('#table_share');
                // 初始化表格
                table.bootstrapTable({
                    data: shareCoupon,
                    pk: 'id',
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    showExport: false, //是否可导出数据
                    columns: [
                        [
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: table,
                                events: Table.api.events.operate,
                                formatter: function (value, row, index) {
                                    var html = '<a href="javascript:$(\'#table_share\').bootstrapTable(\'remove\',{field: \'id\', values: ['+row.id+']});shareCoupon = shareCoupon.filter(function(item){return item.id != '+row.id+';});" class="btn btn-xs btn-danger"  data-original-title="删除"><i class="fa fa-trash">删除</i></a>'
                                    return html;
                                }
                            },
                            {field: 'name', title: __('Coupon_name'), operate: 'LIKE'},
                            {field: 'send_number', title: __('Gift quantity'),formatter: function(value, row, index) {
                                    return '<input name="row[share_coupon_send]['+index+'][id]" value="'+row.id+'" type="hidden" />' +
                                        '<input name="row[share_coupon_send]['+index+'][id]" value="'+row.id+'" type="hidden" />' +
                                        '<input data-rule="required;integer;range(0~);" name="row[share_coupon_send]['+index+'][send_number]" type="number" style="width: 100px" class="form-control" min="1" value="' + value + '" onchange="javascript:shareCoupon['+index+'].send_number = this.value" /> ';
                                }},
                            {field: 'money', title: __('Preferential content'), operate: false, formatter: function (value, row, index) {
                                    return __('%s yuan less than %s yuan',row.limit,row.money);
                                }},
                            {field: 'validity', title: __('Validity'), operate:false,formatter: function (value, row, index) {
                                    if(parseInt(row.validity_type) === 1){
                                        if(row.validity_days > 0){
                                            return __('Valid for %s days after receiving',row.validity_days);
                                        }else{
                                            return __('Permanently valid');
                                        }
                                    }else{
                                        return row.start_time_text + ' - ' + row.end_time_text;
                                    }
                                }},
                        ]
                    ],

                });
            }
        }
    };
    return Controller;
});
